package com.ruoyi.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.DTO.TeamBO;
import com.ruoyi.common.core.domain.DTO.TeamVO;
import com.ruoyi.common.core.domain.entity.InviteRecord;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.InviteRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Component
public class InviteRecordService {
    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private InviteRecordService inviteRecordService;

    public void insertInviteRecord(InviteRecord inviteRecord) {
        inviteRecordMapper.insert(inviteRecord);
    }

    public InviteRecord selectByInviteeId(Long inviteeId) {
        return inviteRecordMapper.selectByInviteeId(inviteeId);
    }

    public List<Long> selectByInviterId(Long inviterId) {
        return inviteRecordMapper.selectInviteeIdsByInviterId(inviterId);
    }

    /**
     * 查询我的团队12级之内总人数
     */
/*    public Integer selectTeamSize(Long userId){
        //查询我的团队顶级人id
//        InviteRecord inviteRecord = inviteRecordMapper.selectByInviteeId(userId);
//        Long beginLevel = inviteRecord.getLevel()+1;
//        Long endLevel = beginLevel+12;
        //查询我的团队总人数
//        return inviteRecordMapper.selectTeamSize(userId,beginLevel,endLevel);

//    Integer teamSize = 0;
//List<Long> inviteeIds = inviteRecordMapper.selectInviteeIdsByInviterId(userId);
    }*/


    //根据邀请人id查询邀请数量
   /* public Integer selectTeamSizeByInviteeId(Integer teamSize,Long inviteeId){
        List<InviteRecord> inviteRecords = inviteRecordMapper.selectTeamSizeByInviteeId(inviteeId);
        Integer countNumber = inviteRecords.size();
        if(countNumber==0){
            return teamSize;
        }
        inviteRecords.forEach(inviteRecord -> {
            selectTeamSizeByInviteeId(teamSize + countNumber, inviteRecord.getInviteeId());
        });
        return teamSize;
    }*/
    //查询团队总人数
    public Integer getTotal(Integer teamSize, Long inviteeId) {
        Integer level = inviteRecordMapper.getLevelByInviteeId(inviteeId);
        return selectTeamSizeByInviterId(teamSize, inviteeId, level + 12);
    }

    //递归查询下级团队总人数
    public Integer selectTeamSizeByInviterId(Integer teamSize, Long inviteeId, Integer level) {
        // 1. 查询当前 inviteeId 的直接下级
        List<InviteRecord> inviteRecords = inviteRecordMapper.selectTeamSizeByInviterId(inviteeId, level);

        // 2. 如果没有下级，直接返回 teamSize
        if (inviteRecords.isEmpty()) {
            return teamSize;
        }

        // 3. 递归计算每个下级的团队大小，并累加
        int totalAdditionalSize = 0;
        for (InviteRecord record : inviteRecords) {
            totalAdditionalSize += selectTeamSizeByInviterId(1, record.getInviteeId(), level); // 1 表示每个下级自己算 1 人
        }

        // 4. 返回当前层级的人数 + 所有下级的总人数
        return teamSize + totalAdditionalSize;
    }

    //查询当前用户团队下级所有用户id
    public List<Long> selectTeamUserIds(Long inviterId) {
        Integer level = inviteRecordMapper.getLevelByInviteeId(inviterId);
        List<Long> directUserIds = new ArrayList<>();
        return selectTeamUserIdByInviterId(directUserIds, inviterId, level + 12, inviterId);
    }

    //查看团队当天新增数量
    public Long selectTeamAddition(Long userId){
        Long teamAddition = 0L;
        //查询团队下级所有用户id
        Integer level = inviteRecordMapper.getLevelByInviteeId(userId);
        List<Long> directUserIds = new ArrayList<>();
        List<Long> userIds = selectTeamUserIdByInviterId(directUserIds, userId, level + 12, userId);
        if(ObjectUtils.isEmpty(userIds)){
            return teamAddition;
        }
        //查询当日新增数量
        teamAddition = sysUserMapper.selectTeamAddition(userIds);
        return teamAddition;
    }

    //递归查询下级团队总人数
    public List<Long> selectTeamUserIdByInviterId(List<Long> directUserIds, Long inviterId, Integer level, Long loginUserId) {
        // 1. 查询当前 inviteeId 的直接下级
        List<InviteRecord> inviteRecords = inviteRecordMapper.selectTeamSizeByInviterId(inviterId, level);

        // 2. 如果没有下级，直接返回 teamSize
        if (inviteRecords.isEmpty()) {
            return directUserIds;
        }

        // 3. 递归计算每个下级的团队大小，并累加
        for (InviteRecord record : inviteRecords) {
            if (!record.getInviteeId().equals(loginUserId)) {
                directUserIds.add(record.getInviteeId());
            }
            selectTeamUserIdByInviterId(directUserIds, record.getInviteeId(), level, loginUserId); // 1 表示每个下级自己算 1 人
        }

        // 4. 返回当前层级的人数 + 所有下级的总人数
        return directUserIds;
    }

    //查询当前用户的直属下级用户id
    public List<Long> selectDirectTeamUserIds(Long inviterId) {
        List<Long> directUserIds = new ArrayList<>();
        List<InviteRecord> inviteRecords = inviteRecordMapper.selectTeamSizeByInviterId(inviterId, null);
        if (!ObjectUtils.isEmpty(inviteRecords)) {
            inviteRecords.forEach(inviteRecord -> {
                directUserIds.add(inviteRecord.getInviteeId());
            });
        }
        return directUserIds;
    }

    //查询所有用户，根据用户id可查询下级用户
    public TeamVO selectTeams(TeamBO teamBO) {
        TeamVO teamVO = new TeamVO();
        //如果入参为空，则查询所有用户
        if (ObjectUtils.isEmpty(teamBO.getUserName())) {
            List<SysUser> sysUsers = sysUserMapper.selectUserAll();
            teamVO.setTeam(sysUsers);
            teamVO.setTeamSize(sysUsers.size());
        } else {
            int teamSize = 0;
            //如果参数不为空，则查询当前用户和团队下级用户
            SysUser sysUser = sysUserMapper.selectUserByUserName(teamBO.getUserName());
            teamVO.setUser(sysUser);
            if (!ObjectUtils.isEmpty(sysUser)) {
                teamSize++;
                List<Long> userIds = new ArrayList<>();
                Long userId = sysUser.getUserId();
                //查询该用户团队下级用户
                //获取直属下级人员id
                List<Long> directUserIds = inviteRecordService.selectDirectTeamUserIds(userId);
                if (!ObjectUtils.isEmpty(directUserIds)) {
                    userIds.addAll(directUserIds);
                }
                //获取团队下2级之后12级之内人员id
                List<Long> teamUserIds = inviteRecordService.selectTeamUserIds(userId);
                if (!ObjectUtils.isEmpty(teamUserIds)) {
                    userIds.addAll(teamUserIds);
                }
                if (!ObjectUtils.isEmpty(userIds)) {
                    //根据用户id集合查询用户信息
                    List<SysUser> sysUsers = sysUserMapper.selectUserListByIds(userIds);
                    teamVO.setTeam(sysUsers);
                    teamSize+=sysUsers.size();
                }
            }
            teamVO.setTeamSize(teamSize);
        }
        return teamVO;
    }

    public Long selectMyRecommend(String inviteCode){
       return inviteRecordMapper.selectMyRecommend(inviteCode);
    }
}
